import React, { useState, useEffect } from "react";
import { Table, Button,Modal ,Form,Input } from "antd";
import "./addbtn.less";
import Title from "../../components/Title/Title";
import { Image } from 'antd';
import { getGoodsList, delgoods,updateGoods } from "../../api/goods";

import FileUpload from "./editorImg";
// const FileUpload = ({ onFileChange }) => {
//   const [file, setFile] = useState(null);

//   const handleFileChange = (e) => {
//     const selectedFile = e.target.files[0];
//     setFile(selectedFile);
//     onFileChange(selectedFile);
//   };

//   return (
//     <input type="file" onChange={handleFileChange} />
//   );
// };

const GoodsList = () => {
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({ currentPage: 1, pageSize: 5 });
  const { currentPage, pageSize } = pagination;
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [editedData, setEditedData] = useState({});
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);


//帮我补齐这段代码
const arr = data.map(item => item.goodsDesc);
console.log(arr);







  const handleEditor = (user) => {
    setEditingUser(user);
    setEditedData({ ...user }); // 复制用户数据以便进行修改
    setEditModalVisible(true);
    

  };
  

  const handleEditOk = async () => {
    try {
      const res = await updateGoods(editedData);
      if (res.data.success) {
        console.log(editedData.imgUrl);
        const updatedData = data.map((item) =>
          item.id === editedData.id ? editedData : item
        );
        setData(updatedData);
        setEditModalVisible(false);
      }
    } catch (error) {
      console.error("Failed to update goods:", error);
    }
  };

  const handleEditCancel = () => {
    setEditModalVisible(false);
  };
//  上传图片的文件

  const editModal = (
    <Modal
      title="编辑"
      visible={editModalVisible}
      onOk={handleEditOk}
      onCancel={handleEditCancel}
    >
      <Form >
        <Form.Item label="Name">
          <Input
            value={editedData.name}
            onChange={(e) =>
              setEditedData({ ...editedData, name: e.target.value })
            }
          />
        </Form.Item>
        <Form.Item label="Category">
          <Input
            value={editedData.category}
            onChange={(e) =>
              setEditedData({ ...editedData, category: e.target.value })
            }
          />
        </Form.Item>
        <Form.Item label="Price">
          <Input
            value={editedData.price}
            onChange={(e) =>
              setEditedData({ ...editedData, price: e.target.value })
            }
          />
        </Form.Item>
 
        <Form.Item label="ImgUrl">
          <Input
            value={editedData.imgUrl}
            onChange={(e) =>
              setEditedData({ ...editedData, imgUrl: e.target.value })
            }
          />
               <Image src={editedData.imgUrl} alt="" />

        </Form.Item>


        <Form.Item label="GoodsDesc">
          <Input
            value={editedData.goodsDesc}
            onChange={(e) =>
              setEditedData({ ...editedData, goodsDesc: e.target.value })
            }
          />
        </Form.Item>
   
        {/* Add more Form.Item components for other fields */}
      </Form>
    </Modal>
  );
  // 处理删除商品的函数
  const handeldelgoods = async (id) => {
    try {
      const res = await delgoods(id);
      console.log(res.data);
      // 成功删除后更新数据
      if (res.data.success) {
        // 使用过滤函数来删除对应的数据项
        const newData = data.filter((item) => item.id !== id);
        setData(newData);
        fetchData();
      }
    } catch (error) {
      console.error("Failed to delete goods:", error);
    }
  };
  const columns = [
    {
      id:1,
      title: "商品名称",
      dataIndex: "name",
      key: "name",
    },
    {
      id:2,
      title: "商品分类",
      dataIndex: "category",
      key: "category",
    },
    {
      id:3,
      title: "商品价格",
      dataIndex: "price",
      key: "price",
    },
    {
      id:4,
      title: "商品图片",
      dataIndex: "imgUrl",
      key: "imgUrl",
      render: (imgUrl) => (
        <img src={`http://8.137.157.16:9002${imgUrl}`} alt="" />
      ),
    },
    {
      id:5,
      title: "商品描述",
      dataIndex: "goodsDesc",
      key: "goodsDesc",
      // "goodsDesc": "不错的商品",
      // "rating": 100,
      // "sellCount": 288
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (text, record) => (
        <>
          <Button type="default" onClick={() => handleEditor(record)}>
            编辑
          </Button>
          <Button
            type="primary"
            danger
            onClick={() => handeldelgoods({ id: record.id })}
          >
            删除
          </Button>
        </>
      ),
    },
  ];
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination({
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  const fetchData = async () => {
    try {
      const res = await getGoodsList({ currentPage, pageSize });
      if (Array.isArray(res.data.data)) {
        setData(res.data.data);
        console.log(res.data);
      }
    } catch (error) {
      console.error("Error fetching goods:", error);
    }
  };

  useEffect(() => {
 

    fetchData();
  }, [currentPage, pageSize,data]);

  return (
    <>
      <div className="gdlist">
        <div className="addgd">
          <Title title="商品列表"></Title>
        </div>
        {editModal}
        <Table
        
          columns={columns}
          expandable={{
            expandedRowRender: (record) => (
              <p
                style={{
                  margin: 5,
                }}
              >
                <div className="detail">
                  <div className="desc">
                  商品描述：{record.goodsDesc}
                  </div>
                  <div className="name">
                  商品名：{record.name} </div>
         
           
                </div>
      
              </p>
            ),
        
          }}
          dataSource={data}
          pagination={{
            current: pagination.currentPage,
            pageSize: pagination.pageSize,
            total: 500,
          }}
          onChange={handleTableChange}
        />
      </div>
    </>
  );
};

export default GoodsList;
